package com.xiaobias;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.*;

public class Acceptor extends ServerThread {

    private final ServerSocketChannel serverSocketChannel;

    private final Server server;

    private final Collection<PollerIO> pollerIOs;

    private Iterator<PollerIO> ioIterator;

    public Acceptor(String acceptor, Server server, Set<PollerIO> ioThreads) throws Exception {
        super(acceptor);
        this.server = server;
        this.serverSocketChannel = ServerSocketChannel.open();
        // bind port
        this.serverSocketChannel.configureBlocking(false);
        this.serverSocketChannel.socket().bind(new InetSocketAddress(server.getPort()));
        // register to selector
        this.serverSocketChannel.register(this.selector, SelectionKey.OP_ACCEPT);

        this.pollerIOs = Collections.unmodifiableList(new ArrayList<>(ioThreads));
        this.ioIterator =  this.pollerIOs.iterator();
    }

    @Override
    public void run() {
        while (!server.stopped || !serverSocketChannel.socket().isClosed()) {
            try {
                this.selector.select();
                Iterator<SelectionKey> iterator = this.selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    iterator.remove();
                    if (!key.isValid()) {
                        continue;
                    }
                    if (key.isAcceptable()) {
                        doAccept(key);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        closeSelector();
    }

    private void doAccept(SelectionKey key) throws IOException {
        SocketChannel socketChannel = this.serverSocketChannel.accept();
        socketChannel.configureBlocking(false);
        // get pollerIO, than register to selector
        if (!ioIterator.hasNext()) {
            this.ioIterator =  this.pollerIOs.iterator();
        }
        PollerIO pollerIO = ioIterator.next();
        //
        pollerIO.addAcceptedConnection(socketChannel);
    }
}
